(function(app){
	app
		.controller("searchCtrl",["$scope","$ionicScrollDelegate","myFactory",'$http','$state','$stateParams','$location','$ionicHistory','$timeout','$ionicLoading','$rootScope',function($scope,$ionicScrollDelegate,myFactory,$http,$state,$stateParams,$location,$ionicHistory,$timeout,$ionicLoading,$rootScope){
			//参数接收
			var searchParam = $stateParams.searchParam;//获取传递过来的条件查询参数
			var index = $stateParams.index;//获取传递过来的条件查询参数
			var login = $stateParams.login;
			myFactory.loadingHide();
			
			//前端查询界面采用缓存技术保存查询条件进行重新查询，如果没有结果，则从缓存中获取
			if("yes"!=login){
				if(""==searchParam || null==searchParam || undefined==searchParam){
					//var searchParamTemp = sessionStorage.obj;
					//searchParam = JSON.parse(searchParamTemp);
				}
			}
			
			//S2018122906735移动保全新增变更项目及功能的优化需求 add by mqz 20200901 start 
				 var item15_health=sessionStorage.getItem("item15_health");
	             if(item15_health == "true"){
	                 sessionStorage.setItem("item15_health", false);
	             }
	             var item29_health=sessionStorage.getItem("item29_health");
	             if(item29_health == "true"){
	                 sessionStorage.setItem("item29_health", false);
	             }
	             var item30_health=sessionStorage.getItem("item30_health");
	             if(item30_health == "true"){
	                 sessionStorage.setItem("item30_health", false);
	             }
		 	//S2018122906735移动保全新增变更项目及功能的优化需求 add by mqz 20200901 end
			
			
			//参数定义
			var userVirtualId="";//定义虚拟工号，先默认是空
			$("#photo_dev").hide();
			
			$scope.tabFlag = false;
			$scope.data = {
				//tabFlag: true,这里的true没用，下面改变的不是这个值，而是html上的值，ng-class={'weui_navbar_item':true,'active':!tabFlag}，初始化写到上面了
		        checkType: 1,
		        checkTypes:[
		          {
		            id:1,
		            name:'保单号'
		          },
		          {
		            id:2,
		            name:'投保人证件号码'
		          },
		          {
		            id:3,
		            name:'投保人姓名+出生日期'
		          }
		        ],
				policy: [],
				changeList: []
			};
			
			//选项卡切换
			$scope.tabChange1 = function(){
				$scope.tabFlag = false;
			}
			$scope.tabChange2 = function(){
				$scope.tabFlag = true;
			}
			//下拉选框选择改变
			$scope.changeSelect = function(value){
				this.checkType = value;
			}
			//投保人出生日期选择
//			myFactory.getDate('datetime-picker','请选择出生日期');
			myFactory.initDateUtil('datetime-picker','');
			//提交开始日期初始化
//			myFactory.getDate('startDate','请选择提交开始日期');
			myFactory.initDateUtil('startDate','');
			//提交结束日期初始化
//			myFactory.getDate('endDate','请选择提交结束日期');
			myFactory.initDateUtil('endDate','');
			//投保人出生日期、开始结束时间改变函数
			$scope.changeBirthdate = function(){
				var tbrBirthday = $scope.tbrBirthday;
				myFactory.setDateUtil("datetime-picker",tbrBirthday);
			}
			$scope.changeStarDate = function(){
				var startDate = $scope.startDate;
				myFactory.setDateUtil("startDate",startDate);
			}
			$scope.changeEndDate = function(){
				var endDate = $scope.endDate;
				myFactory.setDateUtil("endDate",endDate);
			}
			//保单查询重置按钮
			$scope.resetBtn = function(){
				$scope.bdhNo="";
				$scope.tbrzjhm="";
				$scope.tbrName="";
				$scope.tbrBirthday="";
				$scope.data.checkType = 1;
			}
			//变更查询重置按钮
			$scope.queryModifyReset = function(){
				$scope.bdhNum=""; //保单号
				$scope.startDate=""; //提交开始时间
				$scope.endDate=""; //提交结束时间
				$scope.slhNo=""; //受理号
				$("#handleStatus").val(2);//处理状态
			}
    		
    		//虚拟工号校验	
    		$scope.checkXngh = function(){
    			$("#errorMessgae").html("");
    			var xngh = $("#userVirtualId").val();
    			//先输入的虚拟工号格式进行校验
    			 if (xngh=="null" || xngh.trim()=="") {
    				$("#errorMessgae").html("请输入虚拟工号！");
    		        return;    
    		     }else if(xngh!=""){
    		        var Reg =/^[0-9]{8}$/;
    		        if (!Reg.test(xngh)) {
    		        	$("#errorMessgae").html("请输入8位数字！");
    		        	return; 
    		        }      	
    		     }
    			
    			 var token=sessionStorage.getItem("token");
 				 var timestamp=myFactory.getTimetamp();
    			 var sfis= "userVirtualId-token-timestamp";
    			 var signStr="userVirtualId="+xngh+"&token="+token+"&timestamp="+timestamp;
    			 var sign = myFactory.hex(signStr);
    			 
    			//校验完毕，提交后台校验
    			$http({
					method: 'GET',
					url: app.domain + 'user/restSaveVirtualId.action',
					params: {"userVirtualId":xngh,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						user = response.data.data.user;
						var isExis = response.data.data.isExis;
						if(isExis=="0"){
							$("#errorMessgae").html("请输入正确的虚拟工号！");
						}else if(isExis=="1"){
							modal('close','overmodal','overwindow','closeX');
						}
					}
				}, function errorCallback(response) {
					alert('查询数据失败!');
				});
    		}
    		 //关于若干个item10变更导致的被保人相关信息丢失的问题处理 add by csf 20181206 start
    		if('yes'==index) {//用于重新受理，
    			/**
				 * S2018062604412网联政策630实施相关系统功能改造需求（移动保全2.0增加签约功能）
				 * 新增签约接口的逻辑 add by csf 20180926 start
				 */
    			$rootScope['flag'] ='';
    			//S2019112910966建设银行签约授权功能需求 add by yangyan 20200220 start
    			for (var prop in $rootScope) {
    			    if (prop.substring(0,5) == 'isCon') {
    			        delete $rootScope[prop];
    			    }
    			}
    			//S2019112910966建设银行签约授权功能需求 add by yangyan 20200220 end
    			/**
				 * S2018062604412网联政策630实施相关系统功能改造需求（移动保全2.0增加签约功能）
				 * 新增签约接口的逻辑 add by csf 20180926 end
				 */
    			if ( 1 == sessionStorage.getItem("isChange_insured_item10") ){
					sessionStorage.setItem("isChange_insured_item10", 2);//设置被保人信息修改无效
    				//$cookies.put('item10_LF_Change','C');
    			}
    			//访问后台缓存用户虚拟工号，并借此判定要不要弹框
        		$http({
    				method: 'GET',
    				url: app.domain + 'user/restGetUserInfo.action',
    				headers:{'item10_LF_Change':'C'}, //向后端传递消息item10变更已经撤销，清除后端session中的缓存 
    			}).then(successCallback,errorCallback);
			} else {
				//访问后台缓存用户虚拟工号，并借此判定要不要弹框
	    		$http({
					method: 'GET',
					url: app.domain + 'user/restGetUserInfo.action'
				}).then(successCallback,errorCallback);
			}
    		function successCallback(response) {
				if (response.data.success) {
					//缓存用户不为null时候才赋予虚拟工号，否则不做操作
					if(response.data.data!=null){
						userVirtualId = response.data.data.userVirtualId;
					}

					//测试虚拟工号弹出框
					//userVirtualId="";
					//判断是否弹框
		    		if(userVirtualId==""){
		    			modal('open','overmodal','overwindow','closeX');
		    		}
				}
			}
    		 function errorCallback(response) {
 				alert('查询用户信息失败!');
 			}
     		//关于若干个item10变更导致的被保人相关信息丢失的问题处理 add by csf 20181206 end
			/**
			 * 保单查询
			 */
			$scope.queryPolicyList = function () {
				/*$.showLoading('正在查询,请稍候');
				setTimeout(function() {
					$.hideLoading();
				}, 3000);*/
				
				var bdhNo=$scope.bdhNo; //保单号
				var tbrzjhm=$scope.tbrzjhm;//投保人证件号码
				var tbrName=$scope.tbrName;//投保人 姓名
				var tbrBirthday=$scope.tbrBirthday;//投保人出生日期
				var type = $scope.data.checkType;//查询类型
				
				if(bdhNo==undefined){
					bdhNo="";
				}
				if(tbrzjhm==undefined){
					tbrzjhm="";
				}
				if(tbrName==undefined){
					tbrName="";
				}
				if(tbrBirthday==undefined){
					tbrBirthday="";
				}

				/*if(bdhNo=="000000"){
					console.log("000000测试单");
					$("#photo_dev").show();
					return false;
				}*/
				
				//方式一：通过保单号查询（其他字段置空）
				if(type=='1'){
					//先置空其他无关字段
					tbrzjhm="";
					tbrName="";
					tbrBirthday="";
					$scope.tbrzjhm="";
					$scope.tbrName="";
					$scope.tbrBirthday="";
					$("#tbrzjhm").val("");
					$("#tbrName").val("");
					$("#datetime-picker").val("");
					
					//如果保单号为空
					if(bdhNo==""){
						$.alert({
							 title: '',
							 text: '保单号不能为空！',
							 onOK: function () {
							 //点击确认
							 }
						 });
						return;
					}
					//如果保单号格式不正确
					var Reg =/^[0-9]{8}$/;
			        if (!Reg.test(bdhNo)){
			        	$.alert({
							 title: '',
							 text: '请输入8位数字！',
							 onOK: function () {
							 //点击确认
							 }
						 });
			        	return;       	
			        }
					
				}
				
				//方式二：通过投保人证件号码（其他字段置空）
				if(type=='2'){
					//先置空其他无关字段
					bdhNo="";
					tbrName="";
					tbrBirthday="";
					$scope.bdhNo="";
					$scope.tbrName="";
					$scope.tbrBirthday="";
					$("#bdhNo").val("");
					$("#tbrName").val("");
					$("#datetime-picker").val("");
					
					if(tbrzjhm==""){
						$.alert({
							 title: '',
							 text: '投保人证件不能为空！',
							 onOK: function () {
							 //点击确认
							 }
						 });
						return;
					}
				}
				
				//方式三：通过投保人姓名+出生日期
				if(type=='3'){
					//先置空其他无关字段
					bdhNo=""
					tbrzjhm="";
					$scope.bdhNo=""
					$scope.tbrzjhm="";
					$("#bdhNo").val("");
					$("#tbrzjhm").val("");
					
					if(tbrName=="" || tbrBirthday==""){
						$.alert({
							 title: '',
							 text: '姓名和出生日期不能为空！',
							 onOK: function () {
							 //点击确认
							 }
						 });
						return;
					}	
				}
				
				//CRS个人税收居民身份保全需求 增加控制填写投保人、受益人单次填写问题 add by rqyang 2018-12-08 begin
				sessionStorage.setItem("HOLDER_CRS_ISEXISTS_FLAG", "N");//查询控制投保人CRS填写标识数据初始化
				sessionStorage.setItem("BENFIT_CRS_ISEXISTS_FLAG", "N");//查询控制受益人CRS填写标识数据初始化
				//CRS个人税收居民身份保全需求 增加控制填写投保人、受益人单次填写问题 add by rqyang 2018-12-08 end
				
				/*var objs =[{a:'1dsfds'},{a:'2dsf'}];
				angular.forEach(objs, function(data){
					console.log(data.a);
				});*/
				var timestamp=myFactory.getTimetamp();
				var token=sessionStorage.getItem("token");
				var sfis= "policyNumber-secuityno-name-birthday-token-timestamp";
				var signStr="policyNumber="+bdhNo+"&secuityno="+tbrzjhm+"&name="+encodeURI(tbrName)+"&birthday="+tbrBirthday+"&token="+token+"&timestamp="+timestamp;//encodeURI(tbrName)
				//var sfis= "policyNumber-token-timestamp";
				//var signStr="policyNumber="+bdhNo+"&token="+token+"&timestamp="+timestamp;//encodeURI(tbrName)
				var sign = myFactory.hex(signStr);
				
				myFactory.loadingShow();
				$http({
					method: 'GET',
					url: app.domain + 'query/restQueryPolicyList.action',
					params: {'policyNumber': bdhNo,'secuityno': tbrzjhm,'name': tbrName,'birthday': tbrBirthday,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						//myFactory.loadingHide();

						/*var queryTimeOut = response.data.data.queryTimeOut;
						if(queryTimeOut=="Y"){
							myFactory.loadingHide();
							myFactory.alert("","查询后台数据超时,请稍候再试！","info");
							return false;
						}*/
						
						var clientPermission = response.data.data.clientPermission;
						if(clientPermission=="N"){
							myFactory.loadingHide();
							//myFactory.alert("","检测您的账户没有权限查询保单数据，请退出系统重新登录！","info");
							$.confirm("您输入的虚拟工号为空，请退出系统重新登录！", "", function() {
								console.log("确定，退出系统！");
								//直接退出到XYT2.0
								var data = {
										sessionTimeOut : "No", //"Yes" Session超时 "No":系统正常的返回
										exitSysPage : "1" //"1" 信易通首页  "2":“我”页面
								};
								setTimeout(function() {
									cordova.sino.entryLocalSys(function(){}, data);
								}, 350);
							});
							console.log("取消，return！");
							return false;
						}
												
						$scope.policys = response.data.data.data.policyList;
						if($scope.policys.length==0){
							myFactory.alert("","您名下暂无该查询条件下的客户信息，请重新确认！","info");
						}
						
						//封装查询条件
						searchParamNew = "" ;//首先置空
						searchParamNew ={'tab':'1','bdhNo':bdhNo,'secuityno': tbrzjhm,'name': tbrName,'birthday': tbrBirthday,'type':type};
						
						$scope.searchParamNew = searchParamNew;//绑定到前台
						//$(".scroll").css({"transform":"translate3d(0px, 0px, 0px) scale(1)"})
						$ionicScrollDelegate.scrollTop();//重新将滚动条初始化滚到最上方，解决如果前一次查询后拉到下方，新的查询数据量太少而导致数据全飞出界面
					}
					//$timeout(function(){myFactory.loadingHide();},2000);
					myFactory.loadingHide();
				}, function errorCallback(response) {
					myFactory.alert("","查询数据失败!","info");
					//$timeout(function(){myFactory.loadingHide();},2000);
					myFactory.loadingHide();
				});
			}

			/**
			 * 变更查询
			 */
			$scope.queryModifyRecord = function () {
				var bdhNum=$scope.bdhNum; //保单号
				var startDate=$scope.startDate; //提交开始时间
				var endDate=$scope.endDate; //提交结束时间
				var slhNo=$scope.slhNo; //受理号
				var disposetype=$.trim($("#handleStatus").val()); //处理状态

				if(bdhNum==undefined){
					bdhNum="";
				}
				if(startDate==undefined){
					startDate="";
				}
				if(endDate==undefined){
					endDate="";
				}
				if(slhNo==undefined){
					slhNo="";
				}
				
				//数据检验
				//if(bdhNum=="" && startDate=="" && endDate=="" && slhNo=="" && disposetype=="2"){ //这种查询虽然也能针对只选了状态的查询，但因为数据量庞大会导致光查询时间要用1分多钟，不合理
				if(bdhNum=="" && startDate=="" && endDate=="" && slhNo==""){//这种方式用户除了选状态，还必须至少填写一些内容用于过滤筛选，这样子数据量就比较小，逻辑也比较合理
					$.alert({
						 title: '',
						 text: '请填写查询条件！',
						 onOK: function () {
						 //点击确认
						 }
					 });
					return;
				}
				
				//如果保单号格式不正确
				if(bdhNum!=""){
					var Reg =/^[0-9]{8}$/;
			        if (!Reg.test(bdhNum)){
			        	$.alert({
							 title: '',
							 text: '保单号请输入8位数字！',
							 onOK: function () {
							 //点击确认
							 }
						 });
			        	return;       	
			        }
				}

				//如果提交开始时间或者提交结束时间不为空
				if(startDate!="" || endDate!="" ){
					var newdatea=initDate(startDate);
		    		var newdateb=initDate(endDate);
		    		newdateb.setMonth(newdateb.getMonth());
		    		var month="";
		    		var date="";
		    		if(newdateb.getMonth()<10){
		    			month="0"+newdateb.getMonth();
		    		}else{month=newdateb.getMonth();}
		    		if(newdateb.getDate()<10){
		    			date="0"+newdateb.getDate();
		    		}else{date=newdateb.getDate();}
		    		var is11=newdateb.getFullYear()+"-"+month+"-"+date;
//		    		console.log("开始日期:"+startDate);
//		    		console.log("结束日期:"+endDate);
//		    		console.log("is11:"+is11);
		    		if(startDate>endDate){
		    			$.alert({
							 title: '',
							 text: '开始日期不能大于结束日期！',
							 onOK: function () {
							 //点击确认
							 }
						});
		    			return;
		    		}
		    		
		    		else if((startDate<=endDate) && !(is11>startDate)){
		    			//return true;
		    		}
		    		else {//else if(!((startDate<=endDate)&&!(is11>startDate))){
		    			$.alert({
							 title: '',
							 text: '提交开始日期和提交结束日期的区间不可超过一个月！',
							 onOK: function () {
							 //点击确认
							 }
						});
		    			return;
		    		}
				}

				var token=sessionStorage.getItem("token");
				var timestamp=myFactory.getTimetamp();
				var sfis= "chdrnum-apnum-startapdate-endapdate-disposetype-token-timestamp";
				var signStr="chdrnum="+bdhNum+"&apnum="+slhNo+"&startapdate="+startDate+"&endapdate="+endDate+"&disposetype="+disposetype+"&token="+token+"&timestamp="+timestamp;//encodeURI(tbrName)
				var sign = myFactory.hex(signStr);
				
				myFactory.loadingShow();
				$http({
					method: 'GET',
					url: app.domain + 'history/queryRestModifyRecord.action',
					params: {'chdrnum': bdhNum,'apnum': slhNo,'startapdate': startDate,'endapdate': endDate,'disposetype': disposetype,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						$scope.changeList = response.data.data.mpBatch;
						if($scope.changeList.length==0){
							myFactory.alert("","您名下暂无该查询条件下的保单变更信息，请重新确认！","info");
						}
						
						//日调整日期显示格式  by ZZQ 2018-3-6
						for(var i = 0 ; i<$scope.changeList.length ; i++){
							$scope.changeList[i].appDate = DateTools($scope.changeList[i].appDate);
						}
						
						//封装查询条件
						searchParamNew = "" ;//首先置空
						searchParamNew ={'tab':'2','chdrnum':bdhNum,'apnum': slhNo,'startapdate': startDate,'endapdate': endDate,'disposetype': disposetype};
						
						$scope.searchParamNew = searchParamNew;//绑定到前台
					}
					myFactory.loadingHide();
				}, function errorCallback(response) {
					myFactory.alert("","查询数据失败!","info");
					myFactory.loadingHide();
				});
			}

			$scope.getParamTest = function () {
				//方法中传递参数模板
				$state.go('content',{
					//userInfo:$scope.views.userInfo
					userNameParm:'admin'
				});
			}
			
			//转换日期方法  例如：20170225--->2017-02-25 by zzq 2018-3-6
			function DateTools(date){
				date = String(date) ;
				if($.trim(date)!=""){
					return date.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3");
				}else{
					return date;
				}
			}
			
			//将字符串2017-04-17这种类型转换成Date类型，传至后台时需要
			function initDate(a){
				var newdate=new Date();
			    newdate.setYear(a.split("-")[0]);
			    newdate.setMonth(a.split("-")[1]-1);
			    newdate.setDate(a.split("-")[2]);
			    return newdate;
			}
			
			//查询条件初始化
			var searchParamNew; //用于传输数据
			var tab;//功能选择 1-保单查询 2-变更查询
			if(searchParam!=null){
//				console.log(searchParam);
				tab = searchParam.tab;
				if(tab==1){
					$scope.data.checkType = searchParam.type;//查询类型
					$scope.bdhNo = searchParam.bdhNo; //保单号
					$scope.tbrzjhm = searchParam.secuityno;//投保人证件号码
					$scope.tbrName = searchParam.name;//投保人 姓名
					$scope.tbrBirthday = searchParam.birthday;//投保人出生日期
					$scope.queryPolicyList();
				}
				if(tab==2){
					$scope.tabChange2();//更换模块
					$scope.bdhNum = searchParam.chdrnum;//保单号
					$scope.startDate = searchParam.startapdate;//提交开始时间
					$scope.endDate = searchParam.endapdate; //提交结束时间
					$scope.slhNo = searchParam.apnum; //受理号
					$("#handleStatus").val(searchParam.disposetype); //处理状态
					$scope.queryModifyRecord();
				}
			}

			//退出移动保全
			$scope.exit = function(){
				myFactory.exit();
			}
			$scope.returnXyt = function(){
				var data = {
					sessionTimeOut : "No",
					exitSysPage : "1" //"1" 信易通首页  "2":“我”页面
				};
				setTimeout(function() {
					//cordova.sino.entryLocalSysFromOtherSys(function(){}, data);
					cordova.sino.entryLocalSys(function(){}, data);
				}, 350);
			}

			if('yes'==index) {//用于重新受理，避免用了ionic后一直存在缓存情况，导致更新了数据可能看到的是脏数据
				$scope.data.checkType = 1;//查询类型
				//$scope.bdhNo = ""; //保单号
			}

			$scope.toContentSelect = function (chdrnum01,chdrcoy,searchParam) {
				/*S2022041822029--PIC_双被保险人增额终身寿险产品系统需求 add by huanghk 20220816 start*/
				var token=sessionStorage.getItem("token");
				var timestamp=myFactory.getTimetamp();
				var sfis= "chdrnum-token-timestamp";
				var signStr="chdrnum="+chdrnum01+"&token="+token+"&timestamp="+timestamp;//encodeURI(tbrName)
				var sign = myFactory.hex(signStr);
				myFactory.loadingShow();
				$http({
					method: 'GET',
					url: app.domain + 'query/checkLife2.action',
					params: {'chdrnum': chdrnum01,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
				}).then(function successCallback(response) {
					if (response.data.success) {
						if(response.data.data){
							myFactory.alert("","暂不支持双被保险人保单变更，请重新确认！","info");
						}else{
							$ionicHistory.clearCache().then(function(){ 
								$state.go('content_select',{
									chdrnum01:chdrnum01,chdrcoy:chdrcoy,searchParam:searchParam
								});
							})
						}
					}
					myFactory.loadingHide();
				}, function errorCallback(response) {
					myFactory.alert("","查询数据失败!","info");
					myFactory.loadingHide();
				});
				/*S2022041822029--PIC_双被保险人增额终身寿险产品系统需求 add by huanghk 20220816 end*/
			}

			
			$scope.toHistoryDetail = function (mid,itemid,searchParam) {
				/*$state.go("content_select",{
					chdrnum01:chdrnum01,chdrcoy:chdrcoy,searchParam:searchParam
				},{reload:true}
				);*/
				//$ionicHistory.clearHistory();
				/*$ionicHistory.clearCache().then(function(){
					$state.go('history_detail',{
						mid:mid,
						itemids:itemid,
						searchParam:searchParam
					});
				})*/
				$ionicHistory.clearCache().then(function(){
					$state.go('history_detail',{
						mid:mid,
						itemids:itemid,
						searchParam:searchParam
					});
				});
			}
			
			$scope.photoTest = function () {
				window.location.href = 'photo/index.html?datestamp=' + (new Date()).getTime();
			}

		}])
})(app)